<?php
namespace App\Logic;

class CateLogic
{
	public $m;
	//json字段定义，下面会自动处理输入输出
	private $jsonField = array(
		'custom'		=>	'array',
		'detail'		=>	'array',
	);

	public function __construct()
	{
		$this->m = M('cate');
	}

	public function ls($module)
	{
		$data = $this->m->where(array('module' => $module))->select();
		//转为树，再转回列表，这是为了保证子类在父类的下方。前方显示时利用lv生成层级样式
		$data = list_to_tree($data);
		$list = array();
		tree_to_list($data, '_sub', 'id', $list);
		return array('st' => 1, 'data' => $list);
	}

	public function get($id)
	{
		$id = (int) $id;
		$row = $this->m->find($id);
		foreach($this->jsonField as $field => $type) {
			$row[$field] = json_decode($row[$field], true);
			if(!$row[$field] && $type == 'object') $row[$field] = new \stdClass();
			if(!$row[$field] && $type == 'array') $row[$field] = array();
		}
		return $row;
	}

	public function save($post)
	{
		$id = (int) $post['id'];
		foreach($this->jsonField as $field => $type) {
			$post[$field] = json_encode($post[$field], 256);
			if(!$post[$field] && $type == 'object') $post[$field] = '{}';
			if(!$post[$field] && $type == 'array') $post[$field] = '[]';
		}
		if($id) {
			$rs = $this->m->where("id = $id")->save($post);
			if($rs !== false) {
				json(1);
			}
		}else{
			$post['detail'] = '[{"url":"","name":"","title":"","text":""},{"url":"","name":"","title":"","text":""},{"url":"","name":"","title":"","text":""}]';
			$rs = $this->m->add($post);
			if($rs !== false) {
				json(1, $rs);
			}
		}
		json(0, '保存错误');
	}

	public function del($id)
	{
		$id = (int) $id;
		if(!$id) json(0, '参数错误');
		$row = $this->m->where("id = $id")->find();

		$has_sub = $this->m->where("pid = $id")->find();
		if($has_sub) json(0, '有子分类，不可删除，请先删除子分类');

		if($row['module']) {
			$count = M($row['module'])->where(array('cate_id' => $id))->count();
			if($count){
				json(0, '分类下有内容，不可删除，请先删除分类中的内容');
			}
		}

		$rs = $this->m->where("id = $id")->delete();
		if($rs === false) {
				json(0, '删除失败');
		}else{
			json(1);
		}
	}

	//获取自定义字段
	public function getCustom($id)
	{
		$row = $this->get($id);
		$row['custom'] = singleGroup($row['custom'], 'en');
		return $row;
	}

	//加载分类自定义字段（会继承父类的自定义字段）
	public function custom($id)
	{
		$row = $this->getCustom($id);
		$prow = $this->getCustom($row['pid']);
		$pprow = $this->getCustom($prow['pid']);
		$custom = array_merge($pprow['custom'], $prow['custom'], $row['custom']);
		$custom = array_values($custom);
		foreach($custom as &$c) {
			$c['option'] && $c['option'] = explode("\n", $c['option']);
			$c['ext'] && $c['ext'] = explode("\n", $c['ext']);
		}
		return $custom;
	}

	//保存自定义字段
	public function save_setting($id, $post)
	{
		$rs = $this->m->where(array('id' => $id))->setField('custom', json_encode($post, 256));
		if($rs === false) json(0, '保存自定义字段失败');
		json(1);
	}
}